#include "game_scenario.h"

void SimulationParameters::setDefaultValues()
{
	a_timeStep           = 1.0f / 60.0f;
	a_velocityIterations = 6;
	a_positionIterations = 2;
}

DrawingTool::DrawingTool() : 
		shapeFlag(0x0001), jointFlag(0x0002),
		aabbFlag(0x0004),  pairFlag(0x0008),
		massCenterFlag(0x0010)
{ }


void DrawingTool::setDefaultFlagValues()
{
	a_drawingFlags = shapeFlag + jointFlag;
}

void DrawingTool::setDrawingFlags()
{
	a_drawingMethods.SetFlags(a_drawingFlags);
}

GameScenario::GameScenario()
{
	setupGameWorld();
	setupSimulationParameters();
	setupGameDrawer();
	createGameObjects();
}

GameScenario::~GameScenario()
{
	destroyGameWorld();
}

void GameScenario::setupGameWorld()
{
	b2Vec2 dafault_gravity(0.0f, -9.81f);
	ap_gameWorld = new b2World(dafault_gravity);
}

void GameScenario::setupSimulationParameters()
{
	a_simulationParameters.setDefaultValues();
}

void GameScenario::setupGameDrawer()
{
	ap_gameWorld->SetDebugDraw(&a_drawingTool.a_drawingMethods);
	a_drawingTool.setDefaultFlagValues();
}

void GameScenario::destroyGameWorld()
{
	delete ap_gameWorld;
	ap_gameWorld = NULL;
	delete ap_car;
	ap_car = NULL;
	delete ap_track;
	ap_track = NULL;
}

void GameScenario::createGameObjects()
{
	b2Vec2 car_position(30.0f, -33.0f);
	//b2Vec2 car_position(100.0f, -80.0f);
	ap_car = new Car(ap_gameWorld, car_position);
	b2Vec2 track_position(27.0f, -33.0f);
	ap_track = new Track(ap_gameWorld, track_position);
}

void GameScenario::makeSimulationStep()
{
	a_drawingTool.setDrawingFlags();
	ap_gameWorld->DrawDebugData();
	ap_gameWorld->Step(a_simulationParameters.a_timeStep, 
		               a_simulationParameters.a_velocityIterations, 
					   a_simulationParameters.a_positionIterations); 
	(*ap_viewCenter).Set(ap_car->getCarPosition().x,
						 ap_car->getCarPosition().y);
}

void GameScenario::processPressKeyboardEvent(unsigned char key)
{
	switch (key)
	{
		case 'a':
			ap_car->turnMotorsOnWith(95.0f);
			break;
		case 's':
			ap_car->brake();
			break;
		case 'd':
			ap_car->turnMotorsOnWith(-95.0f);
			break;
	}
}

void GameScenario::processHoldKeyboardEvent(unsigned char key)
{
	switch (key)
	{
		case 'a':
			ap_car->turnMotorsOff();
			break;
		case 's':
			ap_car->turnMotorsOff();
			break;
		case 'd':
			ap_car->turnMotorsOff();
			break;
	}
}

void GameScenario::connectToViewCenterSettings(b2Vec2& r_viewCenter)
{
	ap_viewCenter = &r_viewCenter;
}
